<?php

require_once("connect_to_database.php");


class FileSessionHandler
{
    private $savePath;
    private $user;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function __construct(){
	error_log("========= MAKING NEW SESSION ============");
    }

    function __destruct(){
	error_log("Destroying now========================". $this->user);
    }

    function setUser($user){
        $this->user = $user;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
	if(isset($this->user))
		error_log("i+++++its set, ".$this->user);
	else
		error_log("ITS NOT SET");
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
	

        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

	$query = sprintf("update members set isOnline=0,color=NULL where username='%s'", $this->user);
	$result = mysql_query($query);	
	error_log($query,0);
        return true;
    }

    function gc($maxlifetime)
    {
	
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');
//session_name('login');
//session_start();
//error_log("===================session id: ".session_id());

?>
